package com.ambientrs.bot.gui;

import javax.swing.*;
import java.applet.Applet;
import java.applet.AppletContext;
import java.applet.AppletStub;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;

public class Loader extends JPanel implements AppletStub {

    private static final long serialVersionUID = 1L;
    private Map<String, String> params = new HashMap<String, String>();
    private Applet applet;

    public Loader() {
        try {
            parseParams();
            URLClassLoader loader = new URLClassLoader(new URL[]{new URL(
                    "http://world43.runescape.com/runescape.jar")});
            JPopupMenu.setDefaultLightWeightPopupEnabled(false);
            Class<?> load = loader.loadClass("client"); // use a signed client FIXME
            applet = (Applet) load.newInstance();
            applet.setStub(this);
            applet.init();
            applet.start();
            applet.setSize(768, 503);
            add(applet, BorderLayout.CENTER);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }

    private void parseParams() throws MalformedURLException, IOException {
        // use dat regex FIXME
        BufferedReader in = new BufferedReader(new InputStreamReader(new URL(
                "http://world43.runescape.com/plugin.js").openStream()));
        String line;
        while ((line = in.readLine()) != null) {
            if (line.length() > 17)
                line = line.substring(17);
            else
                continue;
            if (line.contains("par")) {
                String key = line.substring(line.indexOf("nam") + 5,
                        line.lastIndexOf(' '));
                String value = line.substring(line.indexOf("val") + 6,
                        line.lastIndexOf('>'));
                params.put(key, value);
            }
        }
    }

    public void appletResize(int x, int y) {
        applet.setSize(x, y);
    }

    public AppletContext getAppletContext() {
        return null;
    }

    public URL getCodeBase() {
        try {
            return new URL("http://world43.runescape.com/");
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public URL getDocumentBase() {
        try {
            return new URL("http://world43.runescape.com/");
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public String getParameter(String param) {
        return params.get(param);
    }

    public boolean isActive() {
        return true;
    }

}
